package cn.tedu.boot51.controller;

import cn.tedu.boot51.entity.User;
import cn.tedu.boot51.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @Classname: UserController
 * @Author: bromide
 * @CreateTime: 2022/5/16--10:38
 * @Version: V1.0
 * @Description:
 */
@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(@RequestBody User user){
        if (mapper.selectByName(user.getUsername())==null){
            //说明用户名不存在
            mapper.insert(user);
            return 1;
        }else {
            return 2;
        }
    }
    //在参数列表里面声明session  即可得到当前客户端所对应的Session
    @RequestMapping("/login")
    public int login(@RequestBody User user, HttpSession session){
        User u = mapper.selectByName(user.getUsername());
        if (u==null){
            //说明用户名不存在
            return 2;
        }
        if (u.getPassword().equals(user.getPassword())){
            /*
                把当前登录的用户对象保存到会话对象中
                user代表用户输入的信息包括:用户名和密码
                u代表从数据库查询到的信息,包括:id,用户名和密码,昵称
             */
            session.setAttribute("user",u);
            //密码正确
            return 1;
        }else {
            return 3;
        }
    }
    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        User u = (User)session.getAttribute("user");
        return u;
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //把登录成功时保存的user对象删除
        session.removeAttribute("user");
    }
}
